//
//  USChatVoiceCell.m
//  us
//
//  Created by karry on 2025/4/6.
//

#import "USChatVoiceCell.h"
#import "USWaveformView.h"

@interface USChatVoiceCell()

@property (nonatomic,strong) USWaveformView *voiceView;

@end

@implementation USChatVoiceCell

- (void)setupView{
    [super setupView];
    
    self.bubbleView = [UIView new];
    self.bubbleView.layer.cornerRadius = 14;;
    [self.messageContentView addSubview:self.bubbleView];
    
    self.lengthLab = [UILabel new];
    self.lengthLab.font = [UIFont systemFontOfSize:16];
    self.lengthLab.textColor = UIColor.whiteColor;
    [self.bubbleView addSubview:self.lengthLab];
    
    self.playImgView = [[UIImageView alloc] init];
    [self.bubbleView addSubview:self.playImgView];
    
    self.voiceView = [[USWaveformView alloc] initWithFrame:CGRectZero];
    [self.bubbleView addSubview:self.voiceView];
    
    // bubbleView 约束绑定 messageContentView
    [self.bubbleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.messageContentView);
        make.height.equalTo(@42);
    }];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(palyStateChange:) name:USVoicePlayerDidChangeNotification object:nil];

}

- (void)palyStateChange:(NSNotification *)sender{

    USMessageViewModel *viewModel =  sender.object;
    
    if (viewModel != self.messageViewModel) {
        if (self.isPlaying) {
            self.isPlaying = NO;
        }
        return;
    }
    
    self.isPlaying = viewModel.isPlaying;
    
}


- (void)setMessageViewModel:(USMessageViewModel *)messageViewModel{
    [super setMessageViewModel:messageViewModel];
    
    EMVoiceMessageBody *body = (EMVoiceMessageBody *)messageViewModel.message.body;
    self.lengthLab.text = [self formattedDurationStringFromInt:body.duration];
    
    if (messageViewModel.message.direction == EMMessageDirectionSend) {
        self.bubbleView.backgroundColor = [UIColor jk_colorWithHex:0x5297E3];
        self.lengthLab.textColor = UIColor.whiteColor;
        self.playImgView.image = [UIImage systemImageNamed:@"play.circle.fill"];
        self.playImgView.tintColor = UIColor.whiteColor;
        self.voiceView.barColor = UIColor.whiteColor;
        

    }else{
        self.bubbleView.backgroundColor = [UIColor jk_colorWithHex:0xF9F9F2];
        self.lengthLab.textColor = UIColor.blackColor;
        self.playImgView.image = [UIImage systemImageNamed:@"play.circle.fill"];
        self.playImgView.tintColor = UIColor.blackColor;
        self.voiceView.barColor = UIColor.blackColor;
 
    }
    
    if ([messageViewModel.message.ext.allKeys containsObject:@"volumes"]) {
        NSArray *volumes = messageViewModel.message.ext[@"volumes"];
        
        CGFloat voiceWidth = [self voiceWidth:(int)body.duration];
    
        if ([volumes isKindOfClass:[NSString class]]) {
            //安卓传进来的是个字符串
            NSError *error = nil;
            NSData *jsonData = [(NSString *)volumes dataUsingEncoding:NSUTF8StringEncoding];
            volumes = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
        }
        
        self.voiceView.volumes = [self compressedVolumes:volumes maxWidth:voiceWidth barWidth:2 spacing:2];
        
    }
    
 
}

- (NSArray<NSNumber *> *)compressedVolumes:(NSArray<NSNumber *> *)volumes
                                  maxWidth:(CGFloat)voiceViewWidth
                                  barWidth:(CGFloat)barWidth
                                   spacing:(CGFloat)spacing {
    if (volumes.count == 0 || voiceViewWidth <= 0 || barWidth <= 0) {
        return @[];
    }

    // 计算最多能显示多少个条
    NSInteger maxBars = floor((voiceViewWidth + spacing) / (barWidth + spacing));
    maxBars = MAX(1, maxBars); // 至少显示 1 根

    if (volumes.count <= maxBars) {
        return volumes;
    }

    NSMutableArray<NSNumber *> *compressed = [NSMutableArray arrayWithCapacity:maxBars];
    CGFloat groupSize = (CGFloat)volumes.count / maxBars;

    for (NSInteger i = 0; i < maxBars; i++) {
        CGFloat start = i * groupSize;
        CGFloat end = start + groupSize;

        // 求这一组的平均值（或最大值）
        CGFloat sum = 0;
        NSInteger count = 0;
        for (NSInteger j = floor(start); j < ceil(end) && j < volumes.count; j++) {
            sum += volumes[j].floatValue;
            count++;
        }

        CGFloat average = count > 0 ? sum / count : 0;
        [compressed addObject:@(average)];
    }

    return compressed;
}


- (void)setIsPlaying:(BOOL)isPlaying{
    _isPlaying = isPlaying;
    
    NSLog(@"play - %@",@(isPlaying).stringValue);
    
    if (isPlaying) {
        EMVoiceMessageBody *body = (EMVoiceMessageBody *)self.messageViewModel.message.body;
        [self.voiceView startPlayingAnimationWithDuration:body.duration];
    }else{
        [self.voiceView stopPlayingAnimation];
    }
    
    if (isPlaying) {
        self.playImgView.image = [UIImage systemImageNamed:@"pause.circle.fill"];
    }else{
        self.playImgView.image = [UIImage systemImageNamed:@"play.circle.fill"];
    }

    
    
    
}

- (NSString *)formattedDurationStringFromInt:(int)duration {
    int minutes = duration / 60;
    int seconds = duration % 60;
    
    if (minutes > 0) {
        return [NSString stringWithFormat:@"%d’%d”", minutes, seconds];
    } else {
        return [NSString stringWithFormat:@"%d”", seconds];
    }
    
}

- (void)updateLayout{

    [super updateLayout];
      
    EMVoiceMessageBody *body = (EMVoiceMessageBody *)self.messageViewModel.message.body;
    
    CGFloat voiceWidth = [self voiceWidth:(int)body.duration];
    
    if (self.messageViewModel.message.direction == EMMessageDirectionSend) {

        [self.voiceView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.bubbleView);
            make.left.equalTo(self.bubbleView).offset(8);
            make.height.equalTo(@38);
            make.width.equalTo(@(voiceWidth));
        }];

        [self.lengthLab mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.bubbleView);
            make.left.equalTo(self.voiceView.mas_right).offset(8);
        }];


        [self.playImgView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.bubbleView);
            make.left.equalTo(self.lengthLab.mas_right).offset(8);
            make.right.equalTo(self.bubbleView).offset(-8);
            make.width.height.equalTo(@28);
        }];
        
    }else{
     
        
        [self.playImgView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.bubbleView);
            make.left.equalTo(self.bubbleView).offset(8);
            make.width.height.equalTo(@28);
        }];
        
        
        [self.voiceView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.bubbleView);
            make.left.equalTo(self.playImgView.mas_right).offset(8);
            make.height.equalTo(@38);
            make.width.equalTo(@(voiceWidth));
        }];
        
        [self.lengthLab mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.bubbleView);
            make.left.equalTo(self.voiceView.mas_right).offset(8);
            make.right.equalTo(self.bubbleView).offset(-8);
        }];

    }
    
}

- (CGFloat)voiceWidth:(NSInteger)duration {
    
    CGFloat minWidth = 30;   // 最短语音宽度，比如 1s
    CGFloat maxWidth = 165;  // 最长语音宽度，比如 60s

    duration = MAX(1, MIN(duration, 60)); // 限制在 1~60 秒内

    // 线性插值
    CGFloat ratio = (duration - 1) / 59.0;
    
    CGFloat width = minWidth + ratio * (maxWidth - minWidth);

    return round(width);
    
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end
